package com.artifact.mit.mypoint.service.async;

import static com.artifact.mit.mypoint.service.util.FormatHelper.formatDate;
import static com.artifact.mit.mypoint.service.util.FormatHelper.formatNumber;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;

import com.artifact.mit.mypoint.adapter.TransactionHistoryAdapter;
import com.artifact.mit.mypoint.service.ServiceHandler;
import com.artifact.mit.mypoint.service.model.TransactionHistory;
import com.artifact.mit.mypoint.service.model.api.PointHistory;
import com.artifact.mit.mypoint.service.model.api.PointHistory.UserPointBookDetail;
import com.artifact.mit.mypoint.service.util.DefaultMessage;

public class PointHistoryAsync extends AsyncTask<String, Void, PointHistory> {
	
	private ServiceHandler serviceHandler;
	private Context pointHistoryContext;
	private ProgressDialog dialog;
	private ListView pointHistory;

	public PointHistoryAsync(Context context, ListView listView) {
		dialog = new ProgressDialog(context);
		pointHistoryContext = context;
		serviceHandler = new ServiceHandler(context);
		pointHistory = listView;
	}

	protected void onPreExecute() {
		this.dialog.setMessage(DefaultMessage.LOADING);
		this.dialog.show();
	}

	@Override
	protected void onPostExecute(PointHistory result) {
		if (dialog.isShowing()) {
			dialog.dismiss();
		}
		TransactionHistoryAdapter adapter = new TransactionHistoryAdapter(pointHistoryContext);
		for (UserPointBookDetail detail : result.getUserPointBookDetail()) {
			adapter.add(new TransactionHistory(formatDate(detail.getTrxDate()), 
					detail.getTrxDesc(), detail.getTrxNo(), "-", 
					formatNumber(detail.getTrxCredit()), formatNumber(detail.getTrxDebit())));
		}
		pointHistory.setAdapter(adapter);
	}

	@Override
	protected PointHistory doInBackground(String... params) {
		try {
			return serviceHandler.pointHistoryService();
		} catch (Exception e) {
			Log.e(this.getClass().getName(), "Error Promo Service", e);
		}
		return null;
	}
}
